import '../utils/sp_util.dart';
import '../models/perfume_model.dart';
import 'perfume_service.dart';

class LikeCollectionService {
  // 存储键名
  static const String likedPerfumesKey = 'liked_perfumes';
  static const String collectedPerfumesKey = 'collected_perfumes';

  // 获取用户点赞的所有香水ID
  static List<int> getLikedPerfumeIds(int userId) {
    final key = '${likedPerfumesKey}_$userId';
    return SpUtil.getStringList(key)?.map((id) => int.parse(id)).toList() ?? [];
  }

  // 获取用户收藏的所有香水ID
  static List<int> getCollectedPerfumeIds(int userId) {
    final key = '${collectedPerfumesKey}_$userId';
    return SpUtil.getStringList(key)?.map((id) => int.parse(id)).toList() ?? [];
  }

  // 判断香水是否被点赞
  static bool isPerfumeLiked(int userId, int perfumeId) {
    return getLikedPerfumeIds(userId).contains(perfumeId);
  }

  // 判断香水是否被收藏
  static bool isPerfumeCollected(int userId, int perfumeId) {
    return getCollectedPerfumeIds(userId).contains(perfumeId);
  }

  // 获取用户收藏的所有香水
  static Future<List<PerfumeModel>> getUserCollections(int userId) async {
    final collectedIds = getCollectedPerfumeIds(userId);
    final allPerfumes = PerfumeService.getAllPerfumes();
    return allPerfumes
        .where((perfume) => collectedIds.contains(perfume.id))
        .toList();
  }

  // 获取用户点赞的所有香水
  static Future<List<PerfumeModel>> getUserLikes(int userId) async {
    final likedIds = getLikedPerfumeIds(userId);
    final allPerfumes = PerfumeService.getAllPerfumes();
    return allPerfumes
        .where((perfume) => likedIds.contains(perfume.id))
        .toList();
  }

  // 点赞香水
  static Future<bool> likePerfume(int userId, int perfumeId) async {
    final key = '${likedPerfumesKey}_$userId';
    final likedIds = getLikedPerfumeIds(userId);

    // 如果已经点赞过，则取消点赞
    if (likedIds.contains(perfumeId)) {
      return await unlikePerfume(userId, perfumeId);
    }

    // 添加到点赞列表
    likedIds.add(perfumeId);
    final result = await SpUtil.setStringList(
      key,
      likedIds.map((id) => id.toString()).toList(),
    );

    // 更新香水的点赞数
    if (result) {
      await _updatePerfumeLikeCount(perfumeId, true);
    }

    return result;
  }

  // 取消点赞香水
  static Future<bool> unlikePerfume(int userId, int perfumeId) async {
    final key = '${likedPerfumesKey}_$userId';
    final likedIds = getLikedPerfumeIds(userId);

    // 如果未点赞，直接返回成功
    if (!likedIds.contains(perfumeId)) {
      return true;
    }

    // 从点赞列表移除
    likedIds.remove(perfumeId);
    final result = await SpUtil.setStringList(
      key,
      likedIds.map((id) => id.toString()).toList(),
    );

    // 更新香水的点赞数
    if (result) {
      await _updatePerfumeLikeCount(perfumeId, false);
    }

    return result;
  }

  // 收藏香水
  static Future<bool> collectPerfume(int userId, int perfumeId) async {
    final key = '${collectedPerfumesKey}_$userId';
    final collectedIds = getCollectedPerfumeIds(userId);

    // 如果已经收藏过，则取消收藏
    if (collectedIds.contains(perfumeId)) {
      return await uncollectPerfume(userId, perfumeId);
    }

    // 添加到收藏列表
    collectedIds.add(perfumeId);
    final result = await SpUtil.setStringList(
      key,
      collectedIds.map((id) => id.toString()).toList(),
    );

    // 更新香水的收藏数
    if (result) {
      await _updatePerfumeFavoriteCount(perfumeId, true);
    }

    return result;
  }

  // 取消收藏香水
  static Future<bool> uncollectPerfume(int userId, int perfumeId) async {
    final key = '${collectedPerfumesKey}_$userId';
    final collectedIds = getCollectedPerfumeIds(userId);

    // 如果未收藏，直接返回成功
    if (!collectedIds.contains(perfumeId)) {
      return true;
    }

    // 从收藏列表移除
    collectedIds.remove(perfumeId);
    final result = await SpUtil.setStringList(
      key,
      collectedIds.map((id) => id.toString()).toList(),
    );

    // 更新香水的收藏数
    if (result) {
      await _updatePerfumeFavoriteCount(perfumeId, false);
    }

    return result;
  }

  // 更新香水的点赞数
  static Future<void> _updatePerfumeLikeCount(
    int perfumeId,
    bool isIncrease,
  ) async {
    try {
      // 获取香水信息
      final perfumes = PerfumeService.getAllPerfumes();
      final perfumeIndex = perfumes.indexWhere((p) => p.id == perfumeId);

      if (perfumeIndex >= 0) {
        final perfume = perfumes[perfumeIndex];
        final newLikeCount =
            isIncrease
                ? perfume.likeCount + 1
                : perfume.likeCount > 0
                ? perfume.likeCount - 1
                : 0;

        // 创建更新后的香水对象
        final updatedPerfume = PerfumeModel(
          id: perfume.id,
          category: perfume.category,
          userId: perfume.userId,
          title: perfume.title,
          description: perfume.description,
          isRecommend: perfume.isRecommend,
          isVideo: perfume.isVideo,
          url: perfume.url,
          cover: perfume.cover,
          favoriteCount: perfume.favoriteCount,
          likeCount: newLikeCount,
          commentCount: perfume.commentCount,
        );

        // 更新香水信息
        await PerfumeService.updatePerfume(updatedPerfume);
      }
    } catch (e) {
      print('更新香水点赞数失败: $e');
    }
  }

  // 更新香水的收藏数
  static Future<void> _updatePerfumeFavoriteCount(
    int perfumeId,
    bool isIncrease,
  ) async {
    try {
      // 获取香水信息
      final perfumes = PerfumeService.getAllPerfumes();
      final perfumeIndex = perfumes.indexWhere((p) => p.id == perfumeId);

      if (perfumeIndex >= 0) {
        final perfume = perfumes[perfumeIndex];
        final newFavoriteCount =
            isIncrease
                ? perfume.favoriteCount + 1
                : perfume.favoriteCount > 0
                ? perfume.favoriteCount - 1
                : 0;

        // 创建更新后的香水对象
        final updatedPerfume = PerfumeModel(
          id: perfume.id,
          category: perfume.category,
          userId: perfume.userId,
          title: perfume.title,
          description: perfume.description,
          isRecommend: perfume.isRecommend,
          isVideo: perfume.isVideo,
          url: perfume.url,
          cover: perfume.cover,
          favoriteCount: newFavoriteCount,
          likeCount: perfume.likeCount,
          commentCount: perfume.commentCount,
        );

        // 更新香水信息
        await PerfumeService.updatePerfume(updatedPerfume);
      }
    } catch (e) {
      print('更新香水收藏数失败: $e');
    }
  }
}
